package com.dengcj.util;

import weaver.general.GCONST;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author dengchunjie
 * @Description: 业务日志工具类
 * @date 2022/1/10 17:46
 */
public class LogCj {

    //默认日志文件名
    private String log_filename = "debug";

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    public LogCj(){}

    public LogCj(String logFilename){
        setLogFileName(logFilename);
    }

    /**
     * 设置日志文件名
     * @param filename
     */
    public void setLogFileName(String filename){
        if(CjUtil.isNotBlank(filename)) {
            this.log_filename = filename;
        }
    }

    /**
     * 写入日志
     * @param info 文件内容
     */
    public void log(String info) {
        log(info,0);
    }

    /**
     * 写入日志
     * @param info 日志内容
     * @param line 强制换行
     */
    public void log(String info,int line) {
        try {
            Date now = new Date();

            String dateStr = dateFormat.format(now);

            String path = GCONST.getRootPath()+"/cuslog";
            File file = new File(path+File.separatorChar+log_filename+"-"+dateStr+".log");

            if (!new File(path).exists()) {
                file.mkdir();
            }

            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fileWritter = new FileWriter(file, true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);

            String nowStr = dateTimeFormat.format(now);
            bufferWritter.write(nowStr + ": " + info);
            bufferWritter.newLine();
            for(int i=0;i<line;i++){
                bufferWritter.newLine();
            }
            bufferWritter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
